package com.imay.live.activity;

import android.view.View;
import android.view.ViewGroup;

import com.imay.cocos.IMayCocos;

/**
 * Created by jeaman on 2017/5/25.
 */

public abstract class BaseCocosActivity extends BaseRequestActivity {
    private ViewGroup mCocosParentView;
    private int mCocosIndex;

    @Override
    protected void onPause() {
        if (mCocosParentView != null) {
            for (int i = 0; i < mCocosParentView.getChildCount(); i++) {
                View cocosView = mCocosParentView.getChildAt(i);
                if (cocosView == IMayCocos.getInstance().getCocosView()) {
                    mCocosIndex = i;
                }
            }
        }
        IMayCocos.getInstance().onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        if (mCocosParentView != null) {
            ViewGroup cocosParentView = (ViewGroup) IMayCocos.getInstance().getCocosView().getParent();
            if (mCocosParentView != cocosParentView) {
                internalAddCocosView(mCocosParentView, mCocosIndex);
                onCocosViewAddAgain();
            }
//            IMayCocos.getInstance().onResume();
        }

        IMayCocos.getInstance().onResume();
        super.onResume();
    }

    protected void onCocosViewAddAgain() {

    }

    protected void addCocosView(ViewGroup parent) {
        addCocosView(parent, -1);
    }

    //需要在onCreate时添加cocosView，否则onResume生命周期无法对cocosView设置onResume
    protected void addCocosView(ViewGroup parent, int index) {
        mCocosParentView = parent;
        mCocosIndex = index;
        internalAddCocosView(parent, index);
    }

    private void internalAddCocosView(ViewGroup parent, int index) {
//        IMayCocos.getInstance().onPause();
        IMayCocos.getInstance().removeCocosViewParent();
        parent.addView(IMayCocos.getInstance().getCocosView(), index);
    }

    public void removeCocosView() {
        if (mCocosParentView != null) {
            if (mCocosParentView.indexOfChild(IMayCocos.getInstance().getCocosView()) >= 0) {
//                IMayCocos.getInstance().onPause();
                mCocosParentView.removeView(IMayCocos.getInstance().getCocosView());
            }
            mCocosParentView = null;
        }
    }

    @Override
    protected void onDestroy() {
        removeCocosView();
        super.onDestroy();
    }

}
